package it.newinstance.util;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * Utility class for reading configuration files.
 * 
 * @author Luigi R. Viggiano
 * @version $Id: Configuration.java 159 2007-11-15 02:33:39Z luigi.viggiano $
 */
public class Configuration {
    private Properties props = new Properties();
    
    public static Configuration getConfiguration(Class<?> c) {
        return create(c, getPath(c.getName()));
    }
    
    public static Configuration getConfiguration(String path) {
        return create(null, path);
    }

    public static Configuration getConfiguration(Package p) {
        return create(null, getPath(p.getName()));        
    }


    public String getString(String name) {
        return props.getProperty(name);
    }
    
    public String[] getStringArray(String name) {
        String[] elements = getString(name).split(",", -1);
        String[] results = new String[elements.length];        
        for (int i = 0; i < elements.length; i++)              
            results[i] = elements[i].trim();        
        return results;
    }    
    
    public List<String> getList(String name) {
        return Arrays.asList(getStringArray(name));
    }
    
    public int getInt(String name) {
        return Integer.parseInt(getString(name).trim());
    }
    
    private static String getPath(String name) {
        return "/" + name.replace('.', '/') + ".properties";
    }

    private static Configuration create(Class<?> loader, String path) {
        try {
            if (loader == null)
                loader = Configuration.class;
            Configuration result = new Configuration();
            result.props.clear();
            result.props.load(loader.getResourceAsStream(path));
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }        
    }    
}
